﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.UI;
using OutdoorLib.BaseEntity.Infrastructure;
using Grishko.DataTier;
using OutdoorLib.BaseEntity.Contract;
using OutdoorLib.BaseEntity.Filters;

public partial class Ctl_ctlSideSheduleFilterPanel : UserControl , ITimePeriodFilter, IFilterEditor 
{
    private const string CloneFilterKey = "CloneFilterKey";
    private const string CurrentContractIdKey = "CurrentContractIdKey";
            
    protected override void OnInit(EventArgs e)
    {
         
        
            
        base.OnInit(e);
        IitControls();
        if (!IsPostBack)
            CacheTools.ResetSessionCache(CloneFilterKey);
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            DataBind();
            ImChange ();
        }

    }

    public Grishko.UI.SideSheduleTable.SideSheduleParams SideSheduleParams
    {
        get {
            SideSheduleTable.SideSheduleParams result = new SideSheduleTable.SideSheduleParams ();
            result .dtStart =dtStart ;
            result .dtFinish =dtFinish ;
            switch (cmbPeriodType .SelectedIndex)
            {
                case 0:
                    result.Period = Ecopsy.Tools.DateTimeTools.TimePeriod.Month;
                break ;
                case 1:
                    result.Period = Ecopsy.Tools.DateTimeTools.TimePeriod.Week ;
                break;

                case 2:
                result.Period = Ecopsy.Tools.DateTimeTools.TimePeriod.Day;
                break;
            }

            result.CurrentContract = CurrentContract;
            return result ;
            
        }
    }



    protected virtual IFilterPanel FilterPanel
    {
        get { return FilterPanel1; }
    }

    protected virtual IFilterEditor FilterEditor
    {
        get { return this; }
    }


    private void IitControls()
    {
        FilterEditor.DataSource = GetCloneFilterDataSource;
        ctlFilterEditor1.DataSource = GetCloneFilterDataSource;        
        

    }

    Filter _FilterClone = null;
    protected Filter GetCloneFilterDataSource()
    {
        if (null != _FilterClone)
            return _FilterClone;

        if (CacheTools.IsSessionCacheObject(CloneFilterKey))
            _FilterClone = (Filter)CacheTools.GetSessionCacheObect(CloneFilterKey);
        else
        {
            Filter BaseFilter = FilterPanel.DataSource();
            if (null == BaseFilter)
                            return null;

            _FilterClone = (Filter)BaseFilter.Clone();
            CacheTools.SetSessionCacheObject(CloneFilterKey, _FilterClone);
        }

        return _FilterClone;
    }


    ContractEntity _Contract = null;
    public ContractEntity CurrentContract
    {
        get
        {
            if(String .IsNullOrEmpty ( CurrentContractId))
                  return null;

            if (null != _Contract)
            {
                return _Contract;
            }
                         
            if (GlobalConstants.IsNewRecord(CurrentContractId))
            {
                _Contract = (ContractEntity)AppEnvironment.ObjectFactory.GetNewObject("Contract", GlobalConstants.GetNewID(CurrentContractId));
                AppEnvironment.BusinessRules.SetDefaultValue(_Contract, null);
            }
            else
                _Contract = (ContractEntity)AppEnvironment.ObjectFactory.GetObject(CurrentContractId, "Contract");


            return _Contract;
        }
    }
    /// <summary>
    /// ID редактируемого контракта
    /// </summary>
    public string CurrentContractId
    {

        get
        {
            return hfCurrentContractID.Value;            
        }
        set
        {
            hfCurrentContractID.Value= value;
        }
    }

    protected string GetContractRecordImg()
    {
        if (null == CurrentContract)
            return "~/images/contract.png";
        else
            return "~/images/media-record.png";
    }

    protected List<ListItem> ContractTypeSouce
    {
        get
        {
            
            List<ListItem> result = new List<ListItem>();
            foreach (DictionaryItem i in TContractStatus.GetFullList())
            {                                
                ListItem li = new ListItem(i.Value.ToString(), i.ParamID);             
                result.Add(li);
            }
            return result;
        }
    }

    protected void btnShowFilter_Click(object sender, ImageClickEventArgs e)
    {
       //ShowEditor = (!ShowEditor);
        DataBind();
        updFilter.Update();
    }

    protected void btnFind_Click(object sender, ImageClickEventArgs e)
    {     
        ImChange();        
    
    }

    /// <summary>
    /// Формирует новый прототип и делает его текущим контрактом
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnNewContract_Click(object sender, ImageClickEventArgs e)
    {
        if (null == CurrentContract)
            PopPanel_Contract.Show();
        else
            CurrentContractId = string.Empty;
        DataBind();
        ImChange();
        
    }

    

    

    

    #region Члены ITimePeriodFilter

    private ITimePeriodFilter TimePeriodFilterSource
    {
        get
        {
            if (null == DataSource)
                return null;
            return (DataSource() as ITimePeriodFilter);
        }
    }


    public DateTime dtStart
    {
        get
        {
            if (null == TimePeriodFilterSource)
                return GlobalConstants.MaxDate;

            DateTime dt;
            DateTime .TryParse (txtStart .Text ,out dt);



            if (DateTime.MinValue != dt)
                TimePeriodFilterSource.dtStart = dt;

            return TimePeriodFilterSource.dtStart;
        }
        set
        {
            TimePeriodFilterSource.dtStart = value;
        }
    }

    public DateTime dtFinish
    {
        get
        {
            if (null == TimePeriodFilterSource)
                return GlobalConstants.MinDate;

            DateTime dt;
            DateTime.TryParse(txtFinish.Text, out dt);            
            

            if (DateTime.MinValue != dt)
                TimePeriodFilterSource.dtFinish = dt;
            
            return TimePeriodFilterSource.dtFinish;
        }
        set
        {
            TimePeriodFilterSource.dtFinish = value;
        }
    }

    protected string sDtStart
    {
        get { return dtStart.ToShortDateString(); }
    }

    protected string sDtFinish
    {
        get { return dtFinish.ToShortDateString(); }
    }


    #endregion


    #region Члены IFilterEditor

    public Func<Filter> DataSource
    {
        get;
        set;
    }

    public Func<bool> ImChange
    {
        get { return ctlFilterEditor1.ImChange; }
        set { ctlFilterEditor1.ImChange = value; }
    }

    #endregion

    public string txtStartClientID { get { return txtStart .ClientID  ;} }
    public string txtFinishClientID { get { return txtFinish.ClientID; } }
    public string txtCurrentContractID { get { return hfCurrentContractID.ClientID; } }


    public string cmbPeriodTypeClientID { get { return cmbPeriodType.ClientID; } }
    protected void btnCreateNewContract_Click(object sender, EventArgs e)
    {
        //Сформировать контракт по Default
        CurrentContractId = GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString();
        AppEnvironment.BusinessRules.SetDefaultValue(CurrentContract,null);
        
        //Считать форму в контракт
        ContractEntity obj = CurrentContract;
        obj.Number = txtContractNumber.Text;
        obj.Client = ctlClientList_1.CurrentClient;

        if (!string.IsNullOrEmpty(txtStateDate.Text))
        {
            _Contract.ContractStatus = TContractStatus.GetStatus(cmbContractState.SelectedValue);
            _Contract.ContractStatus.Date = Convert.ToDateTime(txtStateDate.Text);
        }
        else
        {
            _Contract.ContractStatus = null;
        }

        //// проверить бизнес правила 
        List<string> CheckResult = AppEnvironment.BusinessRules.CheckUpdate(obj);
        if (0 == CheckResult.Count)
        {
            AppEnvironment.ObjectFactory.SaveObject(obj);
        }
        else
        {
            lblMessage.Text = CheckResult[0];
            lblMessage.Visible = true;
            return;
        }

        // Закрыть модальное окно 
        CurrentContractId = obj.ID;
        DataBind();        
        PopPanel_Contract.Hide();
        updFilter.Update();
        ImChange();  
    }
    protected void TextBox_PostBack1_KeyDownEnter(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// Переход к контракту 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnLoadContract_Click(object sender, ImageClickEventArgs e)
    {
        ContractListFilter FilterControl = new ContractListFilter () ;
        string sUrl = AppEnvironment.PageNavigator.GetEditObjectUrlCommand(FilterControl.ObjectPageKey,
                                                                      CurrentContractId ,
                                                                      FilterControl.Where.EntityTypeTagName,
                                                                      FilterControl.AddUrlHandler_Edit);
        AppEnvironment.PageNavigator.Redirect(sUrl);
        
    }
}
